package com.youthfilmic.yuejian.controller.admin;

import com.sun.tools.example.debug.expr.Token;
import com.youthfilmic.yuejian.dao.*;
import com.youthfilmic.yuejian.domain.*;
import com.youthfilmic.yuejian.service.CertificationService;
import com.youthfilmic.yuejian.service.MobileServiceImpl;
import com.youthfilmic.yuejian.service.SubjectService;
import com.youthfilmic.yuejian.service.UserService;
import com.youthfilmic.yuejian.util.OSSUtil;
import com.youthfilmic.yuejian.util.SaveImageFromUrlThread;
import com.youthfilmic.yuejian.util.StringUtil;
import com.youthfilmic.yuejian.weixin.core.TokenSystem;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

/**
 * Created by youweixi on 15/10/11.
 * 后台控制
 */
@Controller
@RequestMapping("/admin")
public class MainController {
    @Resource
    private CertificationDao certificationDao;
    @Resource
    private UserDao userDao;
    @Resource
    private UserService userService;
    @Resource
    private SubjectDao subjectDao;
    @Autowired
    private CertificationService certificationService;
    @Autowired
    private SubjectService subjectService;
    @Resource
    private ApplicationDao applicationDao;
    @Resource
    private CommentDao commentDao;
    @Resource
    private LoginRecordDao recordDao;

    @ModelAttribute("admin")
    public String redirectAdmin(HttpSession session , HttpServletResponse response) throws IOException {
        if (!"true".equals((String)session.getAttribute("admin"))){
            response.sendRedirect("/admin/login");
        }
        return null;
    }

    @RequestMapping("/index")
    public String showIndex(Model model){
        return "redirect:/admin/certification/list";
    }

    @RequestMapping("/certification/list")
    public String showCertificationList(Model model , @RequestParam(value="page" , required = false) Integer p) {
        if (p == null) p = 1;

        Page<Certification> page = certificationDao.findAll(new PageRequest( p - 1 , 20 , new Sort(Sort.Direction.DESC , "postAt")));
        model.addAttribute("certifications" , page.getContent());

        model.addAttribute("currentPage" , p);
        model.addAttribute("totalPage" , page.getTotalPages());
        return "admin/certification/list";
    }

    @RequestMapping("/certification/handle")
    public String acceptCertification(
            Model model,
            @RequestParam("status") int status,
            @RequestParam(value="reason" , required = false) String reason,
            @RequestParam("certificationId") Long certificationId){
        try {
            if (status == -1) reason = "不好意思，您的申请被拒绝了";
            certificationService.handleCertification(certificationId , status , reason);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/admin/certification/list";
    }

    @RequestMapping("/certification/edit")
    public String showCertificationEdit(
            Model model,
            @RequestParam("certificationId") Long certificationId
    ){
        Certification c = certificationDao.findOne(certificationId);
        model.addAttribute("certification",c);
        model.addAttribute("jobMap", DomainInfo.getJobTimeMap());
        model.addAttribute("cityMap",DomainInfo.getCityMap());
        return "admin/certification/edit";
    }

    /**
     * 更新牛人认证信息
     * */
    @RequestMapping("/certification/edit.do")
    public String DoCertificationEdit(
            Model model,
            @RequestParam("certificationId") Long certificationId,
            @RequestParam(value="file_picUrl" , required = false) MultipartFile pic,
            @RequestParam(value="file_img" , required = false) MultipartFile img,
            Certification certification
    ){
        String purl = null;
        String iurl = null;
        if(pic != null && !pic.isEmpty()){
            try {
                purl = OSSUtil.saveImage(pic, "yuejian/user/pic/" + SaveImageFromUrlThread.getRamdomName() + ".jpg");
                certification.setPicUrl(purl);
            } catch (IOException e) {
                certification.setPicUrl(null);
                e.printStackTrace();
            }
        }
        if(img != null && !img.isEmpty()){
            try {
                iurl = OSSUtil.saveImage(img, "yuejian/user/img/" + SaveImageFromUrlThread.getRamdomName() + ".jpg");
                certification.setImg(iurl);
            } catch (IOException e) {
                certification.setImg(null);
                e.printStackTrace();
            }
        }
        //更新信息
        certificationService.updateCertificationInfo(certificationId, certification);
        return "redirect:/admin/certification/edit?certificationId=" + String.valueOf(certificationId);
    }

    @RequestMapping("/user/list")
    public String showUserList(
            Model model,
            @RequestParam(value="page" , required = false) Integer p
    ){
        if (p == null) p = 1;
        Page<User> page = userDao.findAll(new PageRequest(p - 1, 30 , new Sort(Sort.Direction.DESC , "createData")));
        model.addAttribute("users" , page.getContent());
        model.addAttribute("totalElement" , page.getTotalElements());
        model.addAttribute("currentPage" , p);
        model.addAttribute("totalPage", page.getTotalPages());
        return "admin/user/list";
    }

    @RequestMapping("/user/today/list")
    public String showUserTodayList(
            Model model,
            @RequestParam(value="page" , required = false) Integer p
    ){
        if (p == null) p = 1;
        String d = StringUtil.getDayString(new Date());
        Page<LoginRecord> page = recordDao.findByLoginDayString(d , new PageRequest(p-1,30,new Sort(Sort.Direction.DESC , "lastLoginTime")));
        model.addAttribute("records" , page.getContent());
        model.addAttribute("totalElement" , page.getTotalElements());
        model.addAttribute("currentPage" , p);
        model.addAttribute("totalPage" , page.getTotalPages());
        return "admin/user/list-today";
    }

    @RequestMapping("/user/edit")
    public String showUserEdit(
            Model model,
            @RequestParam("userId") Long userId
    ){
        User user = userDao.findOne(userId);
        model.addAttribute("user", user);
        model.addAttribute("jobMap", DomainInfo.getJobTimeMap());
        model.addAttribute("cityMap", DomainInfo.getCityMap());
        return "admin/user/edit";
    }

    @RequestMapping("/user/edit.do")
    public String doUserEdit(
            Model model,
            @RequestParam("userId") Long userId,
            User user,
            @RequestParam(value="file_picUrl" , required = false) MultipartFile pic,
            @RequestParam(value="file_img" , required = false) MultipartFile img
    ){
        String purl = null;
        String iurl = null;
        if(pic != null && !pic.isEmpty()){
            try {
                purl = OSSUtil.saveImage(pic, "yuejian/user/pic/" + SaveImageFromUrlThread.getRamdomName() + ".jpg");
                user.setPicUrl(purl);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(img != null && !img.isEmpty()){
            try {
                iurl = OSSUtil.saveImage(img, "yuejian/user/img/" + SaveImageFromUrlThread.getRamdomName() + ".jpg");
                user.setImg(iurl);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //更新用户信息
        userService.updateUserInfo(userId, user);
        return "redirect:/admin/user/edit?userId=" + userId;
    }

    @RequestMapping("/subject/list")
    public String showSubjectList(Model model , @RequestParam(value="page" , required = false) Integer p){
        //Page<Certification> page = certificationDao.findAll(new PageRequest( 0 , 20 , new Sort(Sort.Direction.DESC , "postAt")));
        //model.addAttribute("certifications" , page.getContent());
        if (p == null) p = 1;

        Page<Subject> page = subjectDao.findAll(new PageRequest(p - 1, 10, new Sort(Sort.Direction.DESC, "postAt")));
        model.addAttribute("subjects", page.getContent());

        model.addAttribute("currentPage" , p);
        model.addAttribute("totalPage", page.getTotalPages());
        return "admin/subject/list";
    }

    /**
     * 编辑话题
     * */
    @RequestMapping("/subject/edit")
    public String showSubjectEdit(
            @RequestParam("subjectId") Long subjectId,
            Model model
    ){
        Subject subject = subjectDao.findOne(subjectId);
        model.addAttribute("subject",subject);
        model.addAttribute("typeMap" , DomainInfo.getSubjectTypeMap());
        model.addAttribute("durationMap", DomainInfo.getDurationMap());
        return "admin/subject/edit";
    }

    @RequestMapping("/subject/add.do")
    public String doSubjectAdd(
            @RequestParam("userId") Long userId,
            Subject subject
    ){
        //创建话题
        subjectService.createSubject(userId, subject);
        return "redirect:/admin/subject/list";
    }

    @RequestMapping("/subject/add")
    public String showSubjectAdd(
            @RequestParam("userId") Long userId,
            Model model
    ){
        User user = userDao.findOne(userId);
        model.addAttribute("user",user);
        model.addAttribute("subject",new Subject());
        model.addAttribute("typeMap" , DomainInfo.getSubjectTypeMap());
        model.addAttribute("durationMap", DomainInfo.getDurationMap());
        return "admin/subject/add";
    }

    @RequestMapping("/subject/edit.do")
    public String doSubjectEdit(
            @RequestParam("subjectId") Long subjectId,
            Subject subject
    ){
        //更新话题资料
        subjectService.updateSubjectInfo(subjectId, subject);
        return "redirect:/admin/subject/edit?subjectId=" + subjectId;
    }

    @RequestMapping("/subject/handle")
    public String handleSubject(
            Model model,
            @RequestParam("status") int status,
            @RequestParam(value="reason" , required = false) String reason,
            @RequestParam("subjectId") Long subjectId){
        try {
            subjectService.handleSubject(subjectId , status , reason);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/admin/subject/list";
    }

    @RequestMapping("/application/list")
    public String showApplicationList(Model model , @RequestParam(value="page" , required = false) Integer p){
        if (p == null) p = 1;
        //Page<Certification> page = certificationDao.findAll(new PageRequest( 0 , 20 , new Sort(Sort.Direction.DESC , "postAt")));
        //model.addAttribute("certifications" , page.getContent());
        Page<Application> page = applicationDao.findAll(new PageRequest(p - 1, 10, new Sort(Sort.Direction.DESC, "postAt")));
        model.addAttribute("applications" , page.getContent());

        model.addAttribute("currentPage" , p);
        model.addAttribute("totalPage", page.getTotalPages());
        return "admin/application/list";
    }

    @RequestMapping("/application/edit")
    public String showApplicationDetail(
            Model model,
            @RequestParam(value="applicationId") Long applicationId){
        Application application = applicationDao.findOne(applicationId);
        model.addAttribute("application" , application);

        if(application.isStarComment()){
            model.addAttribute("starComment" , commentDao.findOne(application.getStarCommentId()));
        }
        if (application.isUserComment()){
            model.addAttribute("userComment" , commentDao.findOne(application.getUserCommentId()));
        }
        return "admin/application/edit";
    }

    /**
     * 高级属性参数查看
     * */
    @RequestMapping("/advance/show")
    public String showAdvance(Model model){
        model.addAttribute("tokenNum" ,"服务不可用");
        model.addAttribute("tokenValue" , TokenSystem.getTokenValue());
        model.addAttribute("ticketValue" , TokenSystem.getTicketValue());
        return "admin/advance/show";
    }


}
